package com.qm.console.controller.rest;

import com.alibaba.fastjson.JSONObject;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.util.HttpInvokeUtil;
import com.qm.console.controller.dto.BaseRsp;
import com.qm.console.controller.dto.ResultEnum;
import com.qm.console.model.UserInfo;
import com.qm.console.pubdef.constant.UrlConstant;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/**")
public class CommonAppRedirectController {

    private String getAdminer() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser == null ? "" : String.valueOf(activeUser.getUsername());
    }

    @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE,
            RequestMethod.PUT }, value = "")
    public BaseRsp appRedirect(HttpServletRequest request, @RequestBody(required = false) JSONObject req,
                               @RequestParam Map<String, String> param) throws URISyntaxException {
        String path = request.getServletPath();
        String method = request.getMethod().toLowerCase();
        String url = UrlConstant.ApiServerHost + path;
        String body;
        if (param == null) {
            param = new HashMap<>();
        }
        if (req == null) {
            req = new JSONObject();
        }
        req.put("operator", getAdminer());

        switch (method) {
            case "get":
                body = HttpInvokeUtil.httpGet(url, param, null);
                break;
            case "delete":
                body = HttpInvokeUtil.httpDelete(url, param,null);
                break;
            case "post":
                body = HttpInvokeUtil.httpPostJson(url, param, req, UrlConstant.DefaultEncode, null);
                break;
            case "put":
                body = HttpInvokeUtil.httpPutJson(url, req.toJSONString(), UrlConstant.DefaultEncode, null);
                break;
            default:
                throw new BusinessException(ResultEnum.PARA_ERR);
        }
        return JSONObject.parseObject(body, BaseRsp.class);
    }
}
